package com.feng.study.demo;

import com.feng.study.value.User;
import com.google.common.collect.Lists;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: Zeng ShaoYong
 * @Date: 2021-10-13
 * @Description:
 */
public class TestStream {
    public static void main(String[] args) {
        test();

//        testGroupBy();

//        testMatch();
    }

    private static void test() {
        List<Integer> list = Lists.newArrayList(1, 2, 1, 1, 1, 3, 4);
        System.out.println(list.stream().distinct().count());
        System.out.println(list.stream().findFirst().get());
        list.stream().limit(3).forEach(System.out::print);
        Map<Integer, Integer> collect = list.stream().map(p -> p + p * 2).collect(Collectors.toMap(p -> p - 1, Function.identity(), (k, v) -> k));
        System.out.println(collect);
        Map<Integer, List<Integer>> collect1 = list.stream().collect(Collectors.groupingBy(p -> p + 1));
        System.out.println(collect1);

        List<String> list1 = Lists.newArrayList("xiao ming", "lao wang", "wang wu");
        List<String> w = list1.stream().map(p -> p.split(" ")).flatMap(Arrays::stream).collect(Collectors.toList());
        System.out.println(w);
    }

    /**
     * groupBY:收集的时候分组
     */
    private static void testGroupBy() {
        User user = new User();

        List<User> userList = Lists.newArrayList();
        Map<String, List<User>> collect = Optional.ofNullable(userList).orElse(Collections.emptyList())
                .stream().collect(Collectors.groupingBy(p -> p.getGender()));
        int a = 10;
        System.out.println(a);
        System.out.println(collect.get("aa"));
        System.out.println(collect);
    }

    /**
     * anyMatch:判断的条件里，任意一个元素成功，返回true
     * allMatch:判断条件里的元素，所有的都是，返回true
     * noneMatch:与allMatch相反，判断条件里的元素，所有的都不是，返回true
     * count:跟List接口中的 .size() 一样，返回的都是这个集合流的元素的长度，不同的是，
     * 流是集合的一个高级工厂，中间操作是工厂里的每一道工序，我们对这个流操作完成后，可以进行元素的数量的和；
     */
    private static void testMatch() {
        List<Integer> list = Lists.newArrayList(1, 2, 1, 1, 1, 3, 4);
        boolean b = Optional.ofNullable(list).orElse(Collections.emptyList())
                .stream().anyMatch(p -> p == 5);
        boolean b1 = list.stream().allMatch(p -> p == 1);
        boolean b2 = list.stream().noneMatch(p -> p == 5);
        long count = list.stream().filter(p -> p == 1).count();
        System.out.println(b);
        System.out.println(b1);
        System.out.println(b2);
        System.out.println(count);
        System.out.println(list.size());
    }
}
